﻿Imports System.Xml
Imports System.Data.SqlClient

Public Class ajaxGameEngine
    Inherits System.Web.UI.Page

    Public userID As user
    Public matchID As Integer
    Dim objDB As New DBConnect
    Dim systemList(20, 2) As String
    Dim systemCount As Integer
    Dim sql As String
    Dim gameID As Integer
    Dim ds As New DataSet
    Dim ds1 As New DataSet
    Dim sysDS As New DataSet
    Dim sysAttPos(1, 1) As Integer
    Private lblSystem() As Label
    'Private gvSystem() As GridView
    Dim SB As New StringBuilder
    Dim SW As New IO.StringWriter(SB)
    Private sysNameString() As String
    Private sysAttString(20, 1) As String
    Dim totalPlayers As Integer = 0
    Dim card As New Card
    Shared deck As New Deck
    Shared hand As New Deck
    Dim minPlayers As Integer = 2
    Dim playerCount As Integer
    Dim testCount As Integer = 0
    Dim sitArray(5) As user
    Dim dr As SqlDataReader

    Dim dealtCard As New Card

    Dim deckOfCards As Deck
    Public cardArray As ArrayList = New ArrayList()
    Dim cardAction As deckActions

    Dim deckOptions As New Deck 'Option Card Deck
    Dim deckConsequence As New Deck 'Consequence Card Deck
    Dim deckCommons As New Deck 'Commons Pile
    Dim deckDiscard As New Deck 'Discard Pile
    Dim deckPlayerHand As New Deck 'Player hand


    'Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Init
    '    displaySystemLabels()
    'End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Dim partname, partname1 As String
        objDB = Session.Item("db")
        matchID = Session.Item("matchID")
        userID = Session.Item("user")
        gameID = Session.Item("gameID")
        btnSendMsg.Enabled = True
        gvdGcard.Visible = True

        If Application("deckOptions") Is Nothing Then
            Application("deckOptions") = deckOptions
            Application("dealtCard") = dealtCard
            Application("deckCommons") = deckCommons
            Application("deckConsequence") = deckConsequence
            Application("deckDiscard") = deckDiscard
            Application("deckPlayerHand") = deckPlayerHand
            Application("cardArray") = cardArray
        End If

       

        'Dim Sql2, Sql3 As String
        'Sql2 = "SELECT PlayerName FROM Player WHERE ParticipantID = 10"
        'Sql3 = "SELECT PlayerName FROM Player WHERE ParticipantID = 12"
        'ds = objDB.getDataSet(Sql2)
        'ds1 = objDB.getDataSet(Sql3)
        'partname = ds.Tables(0).Rows(0).Item(0).ToString
        'partname1 = ds1.Tables(0).Rows(0).Item(0).ToString

        'Player1.Text = partname
        'Player2.Text = partname1
        'SELECT PlayerName FROM Player WHERE ParticipantID = 10

        'The below code was moved to the Start Game function

        'Dim sqlSstring As String = "SELECT ParticipantID FROM Match_Player WHERE MatchID=" & matchID
        'Dim newDS As DataSet = objDB.getDataSet(sqlSstring)

        'Dim counter As Integer = 0
        'totalPlayers = newDS.Tables(0).Rows().Count
        'While counter < totalPlayers
        '    If userID.participantID = newDS.Tables(0).Rows(counter).Item(0) Then
        '        Session("turnNum") = counter + 1
        '    Else
        '        counter += 1
        '    End If
        'End While

        'Application("turnNumber") = 1

        sysDS = Application("sysDS")

        If Not IsPostBack Then
            ' Application("playerCount") = 0
            'gets all systems that are a part of selected game type.
            'If Application("playerCount") Is Nothing Then
            '    Application("playerCount") = 0
            'Else
            '    Application("playerCount") = Application("playerCount") + 1
            'End If
           
            sql = "SELECT s.SystemID, s.SystemName,a.AttributeName, a.AttributeID, g.InitialValue FROM Attribute a INNER JOIN System_Attribute sa ON a.AttributeID=sa.AttributeID INNER JOIN  System s ON sa.SystemID=s.SystemID INNER JOIN  Game_SystemAttribute g ON sa.SystemID=g.SystemID WHERE g.AttributeID=sa.AttributeID And g.GameID=" & gameID
            sysDS = objDB.getDataSet(sql)
            sysDS.Tables(0).Columns(1).ColumnName = "System Name"
            sysDS.Tables(0).Columns(2).ColumnName = "Attribute Name"
            sysDS.Tables(0).Columns(4).ColumnName = "Value"

            'puts returned dataset into 2 dimensional array, for easy system/attribute lookup when an attribute needs to be modified.
            ReDim sysAttPos(sysDS.Tables(0).Rows.Count - 1, 1)
            For x As Integer = 0 To sysDS.Tables(0).Rows.Count - 1
                sysAttPos(x, 0) = CType(sysDS.Tables(0).Rows(x).Item(0), Integer)
                sysAttPos(x, 1) = CType(sysDS.Tables(0).Rows(x).Item(3), Integer)
            Next
            'Stores the system-attribtue array and dataset in application variables.
            Application("sysAttPos") = sysAttPos
            Application("sysDS") = sysDS

            gvSys.DataSource = sysDS
            gvSys.DataBind()
            Application("sysDS") = sysDS

            gvSys.DataSource = sysDS
            gvSys.DataBind()

            isGameReady()

            Application("Started") = False

            generateCardsInPlay()
        End If

    End Sub
    Protected Sub commonsGrid_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)

    End Sub
    Private Function generateRandNum() As Integer
        'IT SHOULD BE NOTED THAT THE HIGHEST NUMBER WANTED MUST BE ONE LESS THAN THE UPPERBOUND
        'THE RANDOM GENERATOR WILL NEVER HIT THE UPPERBOUND NUMBER
        Dim genNum As System.Random = New System.Random
        Return genNum.Next(1, 7)
    End Function
    Private Function generateRandNum(ByVal lower As Integer, ByVal upper As Integer) As Integer
        'IT SHOULD BE NOTED THAT THE HIGHEST NUMBER WANTED MUST BE ONE LESS THAN THE UPPERBOUND
        'THE RANDOM GENERATOR WILL NEVER HIT THE UPPERBOUND NUMBER
        Dim genNum As System.Random = New System.Random
        Return genNum.Next(lower, upper)
    End Function
    Protected Sub btnLeaveGame_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnLeaveGame.Click, btnLeaveGame.Click, btnLeaveGame.Click, btnLeaveGame.Click
        'Deletes player's entry from Match_Player table and redirects to google.com
        Dim sqlString As String = "DELETE FROM Match_Player WHERE MatchID='" & matchID & "' AND ParticipantID='" & userID.participantID & "'"
        objDB.doUpdate(sqlString)

        Session("matchID") = ""
        Session("gameID") = ""

        Response.Redirect("./Team Ghana/lobby.aspx")
    End Sub
    Protected Sub sitPlayer()
        Dim playercount As Integer
        'Application("PlayerCount").ToString()
        playercount = CInt(Application("PlayerCount").ToString)
        playercount = playercount + 1
        Application("PlayerCount") = playercount
    End Sub
    'Protected Sub UpdateTimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles UpdateTimer.Tick
    '    'This will handle the Ticks of the Timer
    '    'Easy Peasy
    'End Sub

    Protected Sub btnPlayNormal_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnPlayNormal.Click
        Dim objDB As New DBConnect
        Dim Sql2 As String
        Sql2 = "Select * FROM Game_Card"
        gvdGcard.DataSource = objDB.getDataSet(Sql2)
        gvdGcard.DataBind()
        gvdGcard.Visible = True

        'All buttons that end a turn need to have the below statement
        Dim turnNum As Integer = Application("turnNumber")
        If turnNum = totalPlayers Then
            turnNum = 1
        Else
            turnNum += 1
        End If

        Application("turnNumber") = turnNum

        'Play card
        For counter As Integer = 0 To Application("dealtCard").cardSystemID.Count - 1
            Dim cardRule1 = New CardRule(cardIDtxt.Text, Application("dealtCard").cardSystemID(counter).ToString)
            cardRule1.playCard(cardIDtxt.Text, Application("dealtCard").cardSystemID(counter), 1, "enter", Me)
        Next
        'cardAction.getCard()
    End Sub
    Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick, Timer3.Tick
        'Dim objDB As New DBConnect
        'Dim Sql2 As String
        'Sql2 = "Select Message FROM Chat"
        'lstChat.DataSource = objDB.getDataSet(Sql2)
        'lstChat.DataBind()

        If Application("Started") = True Then
            'If there are enough players, the game has started
            If Application("turnNumber") = Session("turnNum") Then
                'Do stuff

                btnGcard.Enabled = True
                btnPlayNormal.Enabled = True
            Else
                'Disable the buttons on the page
                btnGcard.Enabled = False
                btnPlayNormal.Enabled = False
            End If
        Else
            'This means the game does not have enough players yet
        End If
    End Sub
    Protected Sub showCards(ByVal sender As Object, ByVal e As EventArgs) Handles btnHide.Click

        If btnHide.Text = "Hide Cards" Then
            btnHide.Text = "Show Cards"
        Else
            btnHide.Text = "Hide Cards"
            generateCardsInPlay()
        End If
        If gvCardsInPlay.Visible = False Then
            gvCardsInPlay.Visible = True
        Else
            gvCardsInPlay.Visible = False
        End If
    End Sub

    Protected Sub Timer2Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        'regenerate cards in play based on ajax timer
        generateCardsInPlay()
    End Sub
    Protected Sub btnSendMsg_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSendMsg.Click
        'If txtChat.Text = "" Then

        'Else
        '    objDB.doUpdate("Insert into Chat Values('" & txtChat.Text & "','" & DateTime.Now.ToString() & "')")
        '    txtChat.Text = ""
        'End If


        'See above
    End Sub
    Protected Sub Timer3_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer3.Tick
        sysDS = Application("sysDS")
        gvSys.DataSource = sysDS
        gvSys.DataBind()
    End Sub
    'finds which row a card modifies in system gridview 
    Protected Function findsysatt(ByVal systemID As Integer, ByVal attributeID As Integer)
        Dim rowToModify As Integer
        Dim numRows As Integer
        sysAttPos = Application("sysAttPos")
        numRows = (sysAttPos.Length \ 2)

        For i As Integer = 0 To numRows - 1
            If sysAttPos(i, 0) = systemID Then
                If sysAttPos(i, 1) = attributeID Then
                    rowToModify = i
                End If
            End If
        Next
        Return rowToModify
    End Function
    'updates values in gvSys
    Public Sub modifySysAtt(ByVal sysid As Integer, ByVal attId As Integer, ByVal modBy As Integer)
        Dim row As Integer
        Dim ds As DataSet
        Dim oldVal As Integer
        Dim newVal As Integer

        ds = Application("sysDS")
        row = findsysatt(sysid, attId)
        oldVal = CType(ds.Tables(0).Rows(row).Item(4), Integer)
        newVal = oldVal + modBy
        ds.Tables(0).Rows(row).Item(4) = newVal
        Application("gvSys") = ds
    End Sub

    'Cheks attributes and returs true of false. False means the system attribute is greater than cards attribute
    'updates values in gvSys
    Public Function checkSysAtt(ByVal sysid As Integer, ByVal attId As Integer, ByVal cardAttribute As Integer)
        Dim row As Integer
        Dim ds As DataSet
        Dim systemAttributeValue As Integer
        Dim sysAttGreater As Boolean = False

        ds = Application("sysDS")
        row = findsysatt(sysid, attId)
        systemAttributeValue = CType(ds.Tables(0).Rows(row).Item(4), Integer)
        If systemAttributeValue > cardAttribute Then
            sysAttGreater = False
        ElseIf systemAttributeValue < cardAttribute Then
            sysAttGreater = True
        End If

        Return sysAttGreater
    End Function

    Protected Sub btnTest_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnTest.Click
        'this is how you select which attribute to update in teh dataset
        ' Dim test As Integer
        modifySysAtt(4, 1, 10)

        'sysDS.Tables(0).Rows(test).Item(4) = "400"
        'Application("gvSys") = sysDS
    End Sub
    Protected Sub btnGcard_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGcard.Click
        gvdGcard.Visible = True
    End Sub
    'pass seat number from ajax on aspx code, so for example btnseat1 onclick="playersit(1)" and do this for each button! this way
    'we can make a case statement so that if seatno=1 disable that button located in spot 1, 
    'Protected Sub playerSit(ByVal SeatNo As Integer)
    '    count gets incremented
    '    playerCount = playerCount + 1

    '    If enoughPlayers(playerCount) Then
    '        start the game here alex.. reference your method to start the game?
    '    Else
    '        keep the start button disabled or do nothing
    '    End If
    'End Sub

    Protected Function enoughPlayers() As Boolean
        Dim playerz As Integer
        playerz = CInt(Application("playerCount").ToString)
        If minPlayers >= playerz Then
            Return False
        Else
            'if this returns true, it should start the game
            Return True
        End If

    End Function

    'this function will be called by the sit buttons on the aspx page, it will be on a timer and will display a start button based on
    'the condition of whether playercount >=enough players

    Protected Sub playerSitsDown(ByVal index As Integer)
        Dim playercountz As Integer
        sitArray(index) = userID
        playercountz = CInt(Application("PlayerCount").ToString)
        playercountz = playercountz + 1
        Application("sat") = sitArray
        Application("PlayerCount") = CStr(playercountz)
    End Sub

    Protected Sub playerSits()
        Dim playercountz As Integer
        playercountz = CInt(Application("PlayerCount").ToString)
        playercountz = playercountz + 1
        Application("PlayerCount") = CStr(playercountz)
    End Sub
    Private Function goalcard() As String
        Dim t As DataTable = Application("gamegoaltable")
        t.DefaultView.RowFilter = "(gameid = @gameid)".Replace("@gameid", gameID)

        Dim t2 As DataTable = Application("nextgoaltable")
        t2.DefaultView.RowFilter = "(gameid = @gameid)".Replace("@gameid", gameID)

        Dim rowfilter As String = "(gameid = @gameid) and (rank = @rank)". _
            Replace("@gameid", gameID). _
            Replace("@rank", t2.DefaultView(0).Item("nextgoal"))

        Dim nextgoaldesc As String = t.Select(rowfilter)(0).Item("goaldesc")

        'process goalid here
        'MsgBox(nextgoaldesc)


        t2.DefaultView(0).Item("nextgoal") += 1

        'gvdGcard.DataSource = t
        'gvdGcard.DataBind()

        Return nextgoaldesc


    End Function
    Protected Sub btnSit1click()
        If btnRefresh1.Enabled = False Then
            'do nothing someone has already sat there
            Player1.Text = "Already Taken"
        Else
            btnRefresh1.Enabled = False
            'disable btn
            'assign loginID to this place
            Player1.Text = userID.pseudonym.ToString
            Playerg1.Text = goalcard()
            'sitPlayer()
            playerSitsDown(1)
        End If
    End Sub
    Protected Sub btnSit2click()
        If btnRefresh2.Enabled = False Then
            'do nothing someone has already sat there
            Player2.Text = "Already Taken"
        Else
            btnRefresh2.Enabled = False
            'disable btn
            'assign loginID to this place
            Player2.Text = userID.pseudonym.ToString
            Playerg2.Text = goalcard()
            'sitPlayer()
            playerSitsDown(2)
        End If
    End Sub

    Protected Sub btnsit3click()
        If btnRefresh3.Enabled = False Then
            'do nothing someone has already sat there
            Player3.Text = "Already Taken"

        Else
            btnRefresh3.Enabled = False
            'disable btn
            'assign loginID to this place
            Player3.Text = userID.pseudonym.ToString
            Playerg3.Text = goalcard()
            'sitPlayer()
            playerSitsDown(3)
        End If
    End Sub
    Protected Sub btnsit4click()
        If btnRefresh4.Enabled = False Then
            'do nothing someone has already sat there
            Player4.Text = "Already Taken"
        Else
            btnRefresh4.Enabled = False
            'disable btn
            'assign loginID to this place
            Player4.Text = userID.pseudonym.ToString
            Playerg4.Text = goalcard()
            'sitPlayer()
            playerSitsDown(4)
        End If
    End Sub

    Protected Sub btnsit5click()
        If btnRefresh5.Enabled = False Then
            'do nothing someone has already sat there
            lblPlayer5.Text = "Already Taken"
        Else
            btnRefresh5.Enabled = False
            'disable btn
            'assign loginID to this place
            lblPlayer5.Text = userID.pseudonym.ToString
            Playerg5.Text = goalcard()
            'sitPlayer()
            playerSitsDown(5)
        End If
    End Sub

    Protected Sub isGameReady()
        If Application("playerCount") Is Nothing Then
            Application("playerCount") = 0
        End If
        If Application("sat") Is Nothing Then
            Application("sat") = sitArray
        End If
        lblPlayerCount.Text = Application("playerCount").ToString
        isSeatAvailable()

        If enoughPlayers() Then
            btnAjaxStartGame.Enabled = True
            btnAjaxStartGame.ForeColor = Drawing.Color.DeepPink ' l o l
        Else
            'not ready yet
        End If


    End Sub

    Protected Sub btnAjaxStartGame_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAjaxStartGame.Click


        If enoughPlayers() = True Then
            'if there are enough players, it checks to see if the game has already been started
            If Application("Started") = False Then
                'if it has not been started, it starts it
                Application("Started") = True

                Dim sqlSstring As String = "SELECT ParticipantID FROM Match_Player WHERE MatchID=" & matchID
                Dim newDS As DataSet = objDB.getDataSet(sqlSstring)
                'Querying the DB for a list of all players in that match

                Dim counter As Integer = 0
                totalPlayers = newDS.Tables(0).Rows().Count
                While counter < totalPlayers
                    If userID.participantID = newDS.Tables(0).Rows(counter).Item(0) Then
                        Session("turnNum") = counter + 1
                        'If your USERID = that row in the table of total players, your Turn Number = the Counter
                        Exit While
                    Else
                        counter += 1
                    End If
                End While
                'It sets the game's turn number to 1, so if youre player 1 you can go.
                Application("turnNumber") = 1
            End If
        End If
    End Sub

    'checks to see if the spot player attempts to sit down at is available
    Protected Sub isSeatAvailable()
        Dim seatArr(5) As user
        seatArr = Application("sat")

        'super ghetto hard-coding madness
        For i As Integer = 1 To seatArr.Count - 1
            If seatArr(i) Is Nothing Then
                'seat empty, allow player to sit
            Else
                If i = 1 Then
                    btnRefresh1.Enabled = False
                    Player1.Text = seatArr(1).pseudonym.ToString
                ElseIf i = 2 Then
                    btnRefresh2.Enabled = False
                    Player2.Text = seatArr(2).pseudonym.ToString
                ElseIf i = 3 Then
                    btnRefresh3.Enabled = False
                    Player3.Text = seatArr(3).pseudonym.ToString
                ElseIf i = 4 Then
                    btnRefresh4.Enabled = False
                    Player4.Text = seatArr(4).pseudonym.ToString
                ElseIf i = 5 Then
                    btnRefresh5.Enabled = False
                    lblPlayer5.Text = seatArr(5).pseudonym.ToString
                End If
            End If
        Next
    End Sub

    Protected Sub drawCommonsBtn_Click(sender As Object, e As EventArgs) Handles drawCommonsBtn.Click

        'shuffle that deck!!!
        Application("deckCommons").Shuffle()

        'deal that card!!!

        dealtCard = Application("deckCommons").Deal
        Application("dealtCard") = dealtCard
        cardIDtxt.Text = dealtCard.ID.ToString
        cardNameLbl.Text = dealtCard.Name
        cardDescriptionLbl.Text = dealtCard.Description

    End Sub

    Protected Sub drawOptionBtn_Click(sender As Object, e As EventArgs) Handles drawOptionBtn.Click
        createOptionsDeck()


        deckOptions = Application("deckOptions")

        'shuffle that deck!!!
        deckOptions.Shuffle()

        'deal that card!!!
        dealtCard = deckOptions.Deal
        Application("dealtCard") = dealtCard
        Application("deckOptions") = deckOptions
        cardIDtxt.Text = dealtCard.ID.ToString
        cardNameLbl.Text = dealtCard.Name
        cardDescriptionLbl.Text = dealtCard.Description
    End Sub

    Public Sub createOptionsDeck()
        Dim cardID As Integer
        cardID = 1
        Dim arrayList As New ArrayList
        arrayList.Add(cardID)

        objDB = Session.Item("db")

        deckOptions = Application("deckOptions")

        If deckOptions.hasCards Then
            deckOptions.removeAllCards()
        End If

        Dim sqlCommand As String

        sqlCommand = "SELECT DISTINCT Card.CardID, Card.CardName, Card.CardCategoryID, Card.CardInstruction, Card.CardDesc, CardPlayAttribute_SystemAttribute.SystemID FROM card, CardPlayAttribute_SystemAttribute WHERE card.CardID = CardPlayAttribute_SystemAttribute.CardID And  CardPlayAttribute_SystemAttribute.SystemID = 1 And  card.CardCategoryID = 1"
        ds = objDB.getDataSet(sqlCommand)

        Dim numOfCards = ds.Tables(0).Rows.Count()

        For i As Integer = 0 To (numOfCards - 1)
            Dim instruction As String
            Dim description As String

            If IsDBNull(ds.Tables(0).Rows(i)("CardInstruction")) Then
                instruction = ""
            Else
                instruction = ds.Tables(0).Rows(i)("CardInstruction")
            End If

            If IsDBNull(ds.Tables(0).Rows(i)("CardDesc")) Then
                description = ""
            Else
                description = ds.Tables(0).Rows(i)("CardDesc")
            End If

            card = New Card(ds.Tables(0).Rows(i)("CardID"), ds.Tables(0).Rows(i)("CardCategoryID"), ds.Tables(0).Rows(i)("CardName"), instruction, description)
            card.cardSystemID = arrayList
            deckOptions.Add(card)
        Next

        Application("deckOptions") = deckOptions
    End Sub

    Protected Sub generateCardsInPlay()
        'regenerates gridview for cards in play

        Dim objDB As New DBConnect
        Dim Sql2 As String
        Dim cardArray1 As ArrayList = Application("cardArray")
        Dim usersCards As UserCards

        Sql2 = "SELECT CardName, CardInstruction, CardDesc FROM Card where CardID="
        For counter As Integer = 0 To cardArray1.Count - 1
            'Assign user cards to an object so we can determine which user has which cards
            usersCards = cardArray1(counter)
            If counter > 0 And userID.participantID.Equals(usersCards.userID) Then
                Sql2 = Sql2 & " OR CardID = " & "'" & usersCards.cardID & "'"
            ElseIf userID.participantID.Equals(usersCards.userID) Then
                Sql2 = Sql2 & "'" & usersCards.cardID & "'"
            End If
        Next
        If cardArray1.Count > 0 Then
            gvCardsInPlay.DataSource = objDB.getDataSet(Sql2)
            gvCardsInPlay.DataBind()
        End If
    End Sub
End Class


'Application("deckOptions") = deckOptions
'Application("dealtCard") = dealtCard
'Application("deckCommons") = deckCommons
'Application("deckConsequence") = deckConsequence
'Application("deckDiscard") = deckDiscard
'Application("deckPlayerHand") = deckPlayerHand


